package com.mall.alipay.service;

import com.mall.alipay.entity.Role;
import com.mall.alipay.entity.UserInfo;
import com.mall.alipay.entity.dto.UserDTO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 *
 */
@Component
public class CustomUserDetailsService implements UserDetailsService{

    @Resource
    private UserInfoService userInfoService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDTO userInfo = userInfoService.getUserInfo(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 添加用户拥有的多个角色
        List<GrantedAuthority> authorities = new ArrayList<>();
        Set<Role> roles = userInfo.getRoles();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRole()));
        }

        return new User(
                userInfo.getAccount(),
                userInfo.getPwd(),
                authorities
        );

    }
}
